package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class RecordTimeAspect {
    private static final Logger log = LoggerFactory.getLogger(RecordTimeAspect.class);

    @Autowired
    private OperateLogMapper operateLogMapper;

    // 定义切点，拦截com.itheima.controller包下的所有方法
    @Around("@annotation(com.itheima.anno.Log)")
    public Object logOperation(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object result = pjp.proceed();

        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;


        // 获取请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取操作人ID（从Session或Token中获取，这里假设从Session中获取）
        Integer operateEmpId = CurrentHolder.getCurrentId();

        // 获取目标类名和方法名
        String className = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();

        // 获取方法参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(pjp.getArgs());

        // 获取返回值
        String returnValue = (result != null ? result.toString() : "void");

        // 创建操作日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(operateEmpId);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(methodParams);
        operateLog.setReturnValue(returnValue);
        operateLog.setCostTime(costTime);

        // 保存日志
        operateLogMapper.insert(operateLog);

        log.info("操作日志已记录: {}", operateLog);
        return result;
    }



}
